package com.yunqiu.dbs;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import org.apache.commons.lang3.StringUtils;

/**
 * java -jar webservice.jar
 */
public class WbsApplication {

    /**
     * 默认数据库类型:mysql
     * mysql/oracle/sqlserver
     */
    private static String url = "";
    private static String type = "";
    private static String body = "";

    public static void main(String[] args) throws IOException {

        byte[] buffer = new byte[1024];
        while (StringUtils.isEmpty(url)){
            System.out.print("请输入请求URL>>");
            System.in.read(buffer);
            url = getInput(buffer);
        }


        while (StringUtils.isEmpty(type)){
            System.out.println("请输入请求类型:GET/POST?(默认GET)>>");
            Arrays.fill(buffer, (byte) 0);
            System.in.read(buffer);
            if("post".equalsIgnoreCase(getInput(buffer))){
                type="POST";
            }else{
                type = "GET";
            }
        }

        if(StringUtils.isNotEmpty(type) && "post".equalsIgnoreCase(type)){
            System.out.println("请输入请求消息体>>");
            Arrays.fill(buffer, (byte) 0);
            System.in.read(buffer);
            body = getInput(buffer);
        }

        //发送请求
        sendRequest();
    }

    public static void sendRequest(){
        if("get".equalsIgnoreCase(type)){
            HttpResponse httpResponse = HttpUtil.createGet(url).execute();
            if(httpResponse.isOk()){
                System.out.println("请求成功");
                System.out.println("请求响应:");
                System.out.println(httpResponse.body());
            }else{
                System.out.println("请求失败,返回码:"+httpResponse.getStatus());
                System.out.println(httpResponse.body());
            }
        }else if("post".equalsIgnoreCase(type)){
            HttpResponse httpResponse = HttpUtil.createPost(url).contentType("application/json").body(body).execute();
            if(httpResponse.isOk()){
                System.out.println("请求成功");
                System.out.println("请求响应:");
                System.out.println(httpResponse.body());
            }else{
                System.out.println("请求失败,返回码:"+httpResponse.getStatus());
                System.out.println(httpResponse.body());
            }
        }else{
            System.out.println("非法请求类型");
        }
    }


    private static String getInput(byte[] buffer) {
        try {
            return new String(buffer, "utf-8").trim();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return "";
        }
    }
}
